﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;
using Microsoft.HomeServer.Extensibility;
using Microsoft.HomeServer.HomeServerConsoleTab.TV4Home.Server.WHS.AddIn.Controls;
using TV4Home.Server.TVEInteractionLibrary.Interfaces;

namespace Microsoft.HomeServer.HomeServerConsoleTab.TV4Home.Server.WHS.AddIn.TabPageControls
{
    public partial class StatusTabUserControl : UserControl
    {
        ITVEInteraction _wcfChannel = null;

        public StatusTabUserControl()
        {
            InitializeComponent();
        }

        private void cmbDataType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbDataType.SelectedIndex == 0)
            {
                RefreshChannelGroups();
                pnChannelGroupId.Visible = true;
            }
            else
            {
                pnChannelGroupId.Visible = false;
            }

            RefreshData();
        }

        private void cmbChannelGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void btnReportBug_Click(object sender, EventArgs e)
        {
            try
            {
                new BugReportForm().Run();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }

        private void RefreshData()
        {
            try
            {
                lvData.Clear();

                switch (cmbDataType.SelectedIndex)
                {
                    case 0:
                        RetrieveTVChannelData();
                        break;

                    case 1:
                        RetrieveTunerData();
                        break;

                    case 2:
                        RetrieveStreamingClientsData();
                        break;

                    case 3:
                        RetrieveRecordingsData();
                        break;

                    case 4:
                        RetrieveSchedulesData();
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                lvData.Clear();

                lvData.Columns.Add(new ColumnHeader() { Text = "Error", Width = this.lvData.Width });
                lvData.Items.Add("Couldn't retrieve data: " + ex.Message);

                this.WcfChannel = null;
            }
        }

        private void RetrieveTVChannelData()
        {
            this.lvData.SmallImageList = tvImageList;

            this.lvData.Columns.Add(new ColumnHeader() { Text = "Name", Width = 200 });
            this.lvData.Columns.Add(new ColumnHeader() { Text = "Current Program", Width = 200 });
            this.lvData.Columns.Add(new ColumnHeader() { Text = "Next Program", Width = 200 });
            this.lvData.Columns.Add(new ColumnHeader() { Text = "", Width = this.lvData.Width - 600 });

            ListViewGroup fta = new ListViewGroup("Free To Air");
            ListViewGroup scrambled = new ListViewGroup("Scrambled");

            this.lvData.Groups.Add(fta);
            this.lvData.Groups.Add(scrambled);

            if (this.cmbChannelGroup.SelectedItem == null)
                return;

            int selectedGroupId = ((KeyValuePair<int, string>)this.cmbChannelGroup.SelectedItem).Key;

            foreach (WebChannelDetailed channel in this.WcfChannel.GetChannelsDetailed(selectedGroupId))
            {
                this.lvData.Items.Add(new ListViewItem(new string[]
                                                           {
                                                               channel.DisplayName,
                                                               channel.CurrentProgram != null ? String.Format("{0} - {1}: {2}", channel.CurrentProgram.StartTime.ToShortTimeString(), channel.CurrentProgram.EndTime.ToShortTimeString(), channel.CurrentProgram.Title) : "",
                                                               channel.NextProgram != null ? String.Format("{0} - {1}: {2}", channel.NextProgram.StartTime.ToShortTimeString(), channel.NextProgram.EndTime.ToShortTimeString(), channel.NextProgram.Title) : ""
                                                           })
                                          {
                                              ImageIndex = channel.FreeToAir == 1 ? 0 : 1,
                                              Group = channel.FreeToAir == 1 ? fta : scrambled
                                          });
            }
        }

        private void RetrieveTunerData()
        {
            this.lvData.Columns.Add(new ColumnHeader() { Text = "Name", Width = 200 });
            this.lvData.Columns.Add(new ColumnHeader() { Text = "Device Path", Width = this.lvData.Width - 200 });

            this.lvData.SmallImageList = tunerImageList;

            foreach (WebCard card in this.WcfChannel.GetCards())
            {
                this.lvData.Items.Add(new ListViewItem(new string[] { card.Name, card.DevicePath })
                {
                    ImageIndex = 0
                });
            }
        }

        private void RetrieveStreamingClientsData()
        {
            this.lvData.Columns.Add(new ColumnHeader() { Text = "IP Address", Width = 200 });
            this.lvData.Columns.Add(new ColumnHeader() { Text = "Stream Name", Width = 200 });
            this.lvData.Columns.Add(new ColumnHeader() { Text = "Date Started", Width = this.lvData.Width - 400 });

            this.lvData.SmallImageList = streamingClientImageList;

            foreach (WebRtspClient client in this.WcfChannel.GetStreamingClients())
            {
                this.lvData.Items.Add(new ListViewItem(new string[] { client.IpAdress, client.StreamName, client.DateTimeStarted.ToString() })
                {
                    ImageIndex = 0
                });
            }
        }

        private void RetrieveRecordingsData()
        {
            this.lvData.Columns.Add(new ColumnHeader() { Text = "Id", Width = 20 });
            this.lvData.Columns.Add(new ColumnHeader() { Text = "File Path", Width = this.lvData.Width - 20 });

            foreach (WebRecording rec in this.WcfChannel.GetRecordings())
            {
                this.lvData.Items.Add(new ListViewItem(new string[] { rec.IdRecording.ToString(), rec.FileName }));
            }
        }

        private void RetrieveSchedulesData()
        {
            this.lvData.Columns.Add(new ColumnHeader() { Text = "Id", Width = 20 });
            this.lvData.Columns.Add(new ColumnHeader() { Text = "Program Name", Width = this.lvData.Width - 20 });

            foreach (WebSchedule sched in this.WcfChannel.GetSchedules())
            {
                this.lvData.Items.Add(new ListViewItem(new string[] { sched.IdSchedule.ToString(), sched.ProgramName }));
            }
        }

        private void RefreshChannelGroups()
        {
            try
            {
                this.cmbChannelGroup.Items.Clear();

                foreach (WebChannelGroup group in this.WcfChannel.GetGroups())
                {
                    this.cmbChannelGroup.Items.Add(new KeyValuePair<int, string>(group.IdGroup, group.GroupName));
                }
            }
            catch (Exception)
            {
                this.WcfChannel = null;
            }
        }

        ITVEInteraction WcfChannel
        {
            get
            {
                if (_wcfChannel == null)
                    _wcfChannel = ChannelFactory<ITVEInteraction>.CreateChannel(new NetNamedPipeBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress("net.pipe://localhost/TV4Home.Server.CoreService/TVEInteractionService"));

                return _wcfChannel;
            }

            set { _wcfChannel = value; }
        }

        private class KeyValuePair<K, V>
        {
            public K Key;
            public V Value;

            public KeyValuePair(K key, V value)
            {
                Key = key;
                Value = value;
            }

            public override string ToString()
            {
                return Value.ToString();
            }
        }
    }
}
